package com.szxy.service.impl;

import com.szxy.mapper.AccountTblExample;
import com.szxy.mapper.AccountTblMapper;
import com.szxy.pojo.AccountTbl;
import com.szxy.service.AccountService;
import io.seata.core.context.RootContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: zwz
 * @Date:2020/7/15 20:55
 * @Description:com.szxy.service
 * @Version:1.0
 **/
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountTblMapper accountTblMapper;

    /**
     * 记录日志
     */
    private static final Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class);

    @Transactional
    @Override
    public void reduceMoney(String userId, int money) {
        logger.info(String.format("开始扣除---> 用户{}，用户金额{}", userId, money));
        // 1. 查询用户是否存在
        AccountTblExample example = new AccountTblExample();
        // where user_id = ?
        example.createCriteria().andUserIdEqualTo(userId);
        List<AccountTbl> accountList = this.accountTblMapper.selectByExample(example);
        if (null == accountList || accountList.isEmpty()) {
            throw new IllegalArgumentException("查询用户不存在 ...");
        }
        // 2. 若用户存在，则钱包金额是否足够
        AccountTbl account = accountList.get(0);
        Integer accountMoney = account.getMoney();
        if (accountMoney < 0 || money > accountMoney) {
            throw new RuntimeException("账户余额不足 ...");
        }
        // 3. 若用户存在，钱包金额也足够，则进行扣除金额操作
        int result = accountMoney - money;
        account.setMoney(result);
        // 更新
        this.accountTblMapper.updateByPrimaryKey(account);
        logger.info(String.format("扣除结束--->用户{}，用户金额剩余{}", userId, result));
        String xid = RootContext.getXID();
        System.out.println("全局事务 xid = " + xid);
        if ("SXT_USER_1".equals(userId)) {
            throw new RuntimeException("远程调用 account 服务失败... 不想成功！ 怎么办？");
        }
    }
}
